package com.xsf.jieyou.commons.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则表达式验证。
 *
 * @author xsf
 * @version v1.0.0
 * @date 2019/11/18 0018 20:03
 * @see com.xsf.jieyou.commons.utils
 **/
public class RegexUtils {
    /**
     * 手机号正则表达式
     */
    private final static String PHONE_REGEX
            = "^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$";
    /**
     * 用户名验证正则表达式
     */
    private final static String USERNAME_REGEX = "^[a-zA-Z0-9-_]{3,20}$";
    /**
     * 密码验证正则表达式
     */
    private final static String PASSWORD_REGEX = "^[a-zA-Z0-9-*/+.~!@#$%^&*-_()]{6,20}$";
    /**
     * 手机验证码正则表达式
     */
    private final static String PHONE_CODE_REGEX = "^[0-9]{4}$";

    /**
     * 手机号验证
     *
     * @return {@link Boolean}
     */
    public static boolean validatePhone(String phone) {
        return isMatch(PHONE_REGEX, phone);
    }

    /**
     * 密码验证
     *
     * @return {@link Boolean}
     */
    public static boolean validatePassword(String phone) {
        return isMatch(PASSWORD_REGEX, phone);
    }

    /**
     * 用户名验证
     *
     * @return {@link Boolean}
     */
    public static boolean validateUsername(String username) {
        return isMatch(USERNAME_REGEX, username);
    }
    /**
     * 手机验证码验证
     *
     * @return {@link Boolean}
     */
    public static boolean validatePhoneCode(String code) {
        return isMatch(PHONE_CODE_REGEX, code);
    }


    private static boolean isMatch(String regex, String original) {
        assert original != null;
        Pattern pattern = Pattern.compile(regex);
        Matcher mat = pattern.matcher(original);
        return mat.matches();
    }


    public static void main(String[] args) {
        System.out.println(validatePhone("13763055759"));
        System.out.println(validateUsername("123456-_"));
        System.out.println(validatePassword("763@#$%^&05575913"));
        System.out.println(validatePhoneCode("1234"));
    }
}
